package com.wangjw.coreTechnology;

import java.util.concurrent.Semaphore;

/**
 * Created by wangjw on 18/7/24.
 */
public class AbnormalSemaphoreSample {

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(0);
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new MyWorker(semaphore));
            thread.start();
        }

        System.out.println("Action...GO!");
        semaphore.release(5);
        System.out.println("Wait for permits off");
        while (semaphore.availablePermits() != 0) {
            Thread.sleep(1000);
        }
        System.out.println("Action...Go again!");
        semaphore.release(5);
    }

    static class MyWorker implements Runnable {

        private Semaphore semaphore;

        public MyWorker(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("Executed!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
